﻿using System;
using Newtonsoft.Json;

namespace InterfaceLiftLib.Converters.Json
{
    public class SafeNumberConverter : JsonConverter
    {
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            throw new NotImplementedException();
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            try
            {
                return reader.Value != null ? Convert.ChangeType(reader.Value, objectType) : Activator.CreateInstance(objectType);
            }
            catch
            {
                return Activator.CreateInstance(objectType);
            }
        }

        public override bool CanConvert(Type objectType)
        {
            return objectType == typeof (int) ||
                   objectType == typeof (long) ||
                   objectType == typeof (float) ||
                   objectType == typeof (double);
        }
    }
}
